package com.ktgj.service.common.JTu;

import com.alibaba.fastjson.JSON;

import com.ktgj.common.core.constant.BusinessTypeConstants;
import com.ktgj.common.core.constant.Constant;
import com.ktgj.common.core.keyutil.AesUtil;
import com.ktgj.common.core.utils.*;
import com.ktgj.service.common.JTu.JTdomain.*;

import org.apache.commons.codec.digest.DigestUtils;

import java.text.MessageFormat;

public class JingTu
{

    // 测试环境
    private final String md5Key = "124d4ebeda5f475f9461443d74778e72";//鲸图出行数据加密key
    private final String tcjtUri = "http://wx.17u.cn/viproom/openapi";//请求地址
    private final String tcjtChannel = "1LLU3PjMh5U=";//渠道号
    private final int tcjtSelfProvider = 200;//同程鲸图自营供应商
    private final int tcjtCooProvider = 201;//同程鲸图联营供应商
    private final int deptid = 1;//厅所属部门

    // 正式环境
//    private final String md5Key = "38cd73a6c2b945f2b53038f6797f62b4";//鲸图出行数据加密key
//    private final String tcjtUri = "http://wx.17u.cn/viproom/openapi";//请求地址
//    private final String tcjtChannel = "CK7yUIfMAl0=";//渠道号
//    private final int tcjtSelfProvider = 428;//同程鲸图自营供应商
//    private final int tcjtCooProvider = 430;//同程鲸图联营供应商
//    private final int deptid = 6991;//厅所属部门

    // 进厅权益开放 
    private final boolean openBigCustomer = true;//是否开放金色大客户使用鲸图厅
    private final boolean openGoldenMember = false;// 是否开放金色会员使用鲸图厅
    private final boolean openKTVipHallOrder = true;// 是否开放空铁订单
    private final boolean openKTMember = false;//是否开放空铁会员
    /// <summary>
    /// 二维码加密密钥
    /// </summary>
    private static String QRCODE_ENCRYPT_KEY = "JSJ!((*)!)!&!)!&";

    /// <summary>
    /// 新版会员二维码 加密密钥
    /// </summary>
    private static String MEMBERCode_MD5_KEY = "12ddsaewtcx#@1";

    private static JingTu instance = null;

    private JingTu()
    {
    }

    public static JingTu getInstance()
    {
        if (instance == null)
        {
            return new JingTu();
        }
        return instance;
    }

    public String getQRCodeKey()
    {
        return this.MEMBERCode_MD5_KEY;
    }

    /**
     * 鲸图出行
     * 获取贵宾厅车站列表、贵宾厅基本详情、商品信息
     * @param stationType
     */
    public void SyncTCJTVipHallData(int stationType)
    {
        try
        {
            // 获取所有车站列表接口
            GetTCJTAirportReq getTCJTAirportReq = new GetTCJTAirportReq();
            getTCJTAirportReq.stationType = stationType;
            getTCJTAirportReq.useRange = null;
            getTCJTAirportReq.channel = tcjtChannel;
            getTCJTAirportReq.version = "1.1";
            String tCJTAirportReq = JSON.toJSONString(getTCJTAirportReq);
            String strAirportList = PostTCJT(tcjtUri + "/queryStationList", tCJTAirportReq);

            GetTCJTAirportListResp airportList = JSON.parseObject(strAirportList, GetTCJTAirportListResp.class);

            if (airportList == null && airportList.msgCode != "100")
            {
                throw new Exception("获取贵宾厅站点列表失败");
            }

            // 获取机场贵宾厅
            for (MoTCJTAirport airport : airportList.data)
            {
                GetTCJTVipHallReq getTCJTVipHallReq = new GetTCJTVipHallReq();
                getTCJTVipHallReq.stationType = stationType;
                getTCJTVipHallReq.useRange = null;
                getTCJTVipHallReq.stationId = airport.stationId;
                getTCJTVipHallReq.channel = tcjtChannel;
                getTCJTVipHallReq.version = "1.1";
                String jsonString = JSON.toJSONString(getTCJTVipHallReq);
                String strVipHallList = PostTCJT(tcjtUri + "/vipRoomDetailList", jsonString);

                GetTCJTVipHallList vipHallList = JSON.parseObject(strVipHallList, GetTCJTVipHallList.class);
                if (vipHallList != null || vipHallList.msgCode == "100")
                {
                    //获取商品详情信息
                    for (MoTCJTVipHall vipHall : vipHallList.data)
                    {
                        GetTCJTVipHallProductReq getTCJTVipHallProductReq = new GetTCJTVipHallProductReq();
                        getTCJTVipHallProductReq.stationType = stationType;
                        getTCJTVipHallProductReq.stationId = airport.stationId;
                        getTCJTVipHallProductReq.roomId = vipHall.roomId;
                        getTCJTVipHallProductReq.channel = tcjtChannel;
                        getTCJTVipHallProductReq.version = "1.1";
                        String toJSONString = JSON.toJSONString(getTCJTVipHallProductReq);
                        String strVipHallProductList = PostTCJT(tcjtUri + "/productDetailList", toJSONString);
                        GetTCJTVipHallProductList vipHallProductList = JSON.parseObject(strVipHallProductList, GetTCJTVipHallProductList.class);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ex.getStackTrace();
        }
    }

    /**
     * 参数请求
     * <param name="uri"></param>
     * <param name="jsonData"></param>
     * <returns></returns>
     * @param uri
     * @param jsonData
     * @return
     */
    public String PostTCJT(String uri, String jsonData)
    {
        String response = "";
        try
        {
            String signContent = jsonData;
            String sign = DigestUtils.md5Hex(signContent+md5Key).toUpperCase();
            response = HttpClientUtil.doPostJsonWithHeader(uri, jsonData, sign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /*public KTTwoDieCodeValidResp checkQRCodeValidTCJT(KTTwoDieCodeValidReq request) {
        KTTwoDieCodeValidResp response = new KTTwoDieCodeValidResp();
        BllBase bllBase = new BllBase();
        try
        {
            //获取渠道厅商品信息
            TcjtVipHall tcjtVIPHall = bllBase._ctx.TcjtVipHalls.stream().filter(t -> t.ProductUniqueCode == request.productUniqueCode).findFirst().orElse(null);
            if (tcjtVIPHall == null || tcjtVIPHall.VipHallId != null)
            {
                throw new Exception("未查询到该同程鲸图贵宾厅数据");
            }
            var vipHall = bllBase._ctx.VIPHalls.Find(tcjtVIPHall.VipHallId.Value);
            if (vipHall == null || vipHall.IsDeleted > 0 || vipHall.VIPHallStatus == EnumHelper.APIEnum.VIPHallStatus.Uavailable)
            {
                throw new JSJException("金色世纪未上线该厅");
            }

            var ticketType = 0;//劵码类型0 大客户活动码 1 金色会员 2空铁在线下单  3 空铁超级空客 等等
            var qrCodesModel = QRCodesModel.InitFromEncryptString(request.ticketNo.Trim());
            if (qrCodesModel != null)
            {
                var isUseNum = false;//会员本人是否扣减次数
                var cardNumber = "";//卡号
                var orderCount = 0;//贵宾厅在线订单数量

                    #region 活动码
                if (qrCodesModel.QRCodesSource == EnumHelper.APIEnum.QRCodesSource.ActivityCode)
                {
                    if (!CheckCanEnterTCJTHall(0))
                    {
                        throw new JSJException("渠道码暂未开放进入鲸图厅");
                    }

                    //判断此渠道码能否使用该厅 一人一码
                    using (var bll = new EmployeeBll())
                    {
                        var model = bll.CheckDimensionCodeTCJT(1, qrCodesModel.Key, tcjtVIPHall.VipHallId.Value);
                        if (model.IsUse == false)
                        {
                            throw new JSJException("当前贵宾厅不在此劵码使用范围内");
                        }
                        if (request.useCount != model.FreeNum)
                        {
                            throw new JSJException("大客户码一人一码，不能多人使用哦");
                        }
                        if (qrCodesModel.Key.StartsWith("UNIONPAY") && qrCodesModel.Key.Length > 16)//广西银联码动态码更换为静态码
                        {
                            qrCodesModel.Key = model.ActivityCode;
                        }
                    }
                }
                    #endregion

                    #region 金色会员到厅
                    else if (qrCodesModel.QRCodesSource == EnumHelper.APIEnum.QRCodesSource.GoldenCenturyApp)
            {
                if (!CheckCanEnterTCJTHall(1))
                {
                    throw new JSJException("不可用，请告知用户微信搜索空铁管家小程序预约后使用。");
                }

                //判断此渠道码能否使用该厅
                if (tcjtVIPHall.UseRange != 1)
                {
                    throw new JSJException("当前贵宾厅不在此劵码使用范围内");
                }

                //todo 会员接口获取会员随行次数

                //var usedEnterHannNum = (request.isSelf == 1 && !thirdResponse.IsUseNum ? request.useCount - 1 : request.useCount);
                //if (thirdResponse.EnterHallNum < usedEnterHannNum)
                //{
                //    var errMessage = string.Format("会员权益可扣减次数仅剩{0}次,本次需要扣减次数{1}", thirdResponse.EnterHallNum, usedEnterHannNum);
                //    //throw new JSJException((errMessage + (usedEnterHannNum != request.useCount ? ",会员本人可免费进厅一次" : "")));
                //    throw new JSJException(errMessage);
                //}
                //cardNumber = thirdResponse.CardId;
                //isUseNum = thirdResponse.IsUseNum;
                ticketType = 1;
            }
                    #endregion

                    #region 贵宾厅订单
                    else if (qrCodesModel.QRCodesSource == EnumHelper.APIEnum.QRCodesSource.AirwayKeeperVipHallOrder)
            {
                // 该厅未开放鲸图设备验证
                if (vipHall.VarifyEquipment != 3) throw new JSJException("渠道码暂未开放进入鲸图厅");

                if (!CheckCanEnterTCJTHall(2))
                {
                    throw new JSJException("渠道码暂未开放进入鲸图厅");
                }boundBankCardList
                long orderNumber;
                long.TryParse(qrCodesModel.Key, out orderNumber);
                if (orderNumber == 0)
                {
                    throw new JSJException("暂不支持进入鲸图厅");
                }
                using (var bll = new OrderBll())
                {
                    bll.CheckOrderVipHallOfTCJT(orderNumber, tcjtVIPHall.VipHallId.Value, tcjtVIPHall.PackServiceId, request.useCount,out orderCount);
                }
                ticketType = 2;
            }
                    #endregion

                    #region 超级空客进厅
                    else if (qrCodesModel.QRCodesSource == EnumHelper.APIEnum.QRCodesSource.AirwayKeeperKongKer)
            {
                if (!CheckCanEnterTCJTHall(3))
                {
                    throw new JSJException("渠道码暂未开放进入鲸图厅");
                }
                using (var orderBll = new OrderBll())
                {
                    cardNumber = orderBll.CheckKTCardOfTCJT(qrCodesModel.Mobile, tcjtVIPHall.VipHallId.Value,
                            tcjtVIPHall.PackServiceId, request.isSelf, request.useCount).ToString();

                    ticketType = 3;
                }
            }
                    #endregion

                    #region 其他
                    else
                {
                    throw new JSJException("渠道码暂未开放进入鲸图厅");
                }
                    #endregion

                string serialID = "";

                    #region 活动码使用
                if (ticketType == 0)
                {
                    var order = _ctx.OrderChannelVipHalls.FirstOrDefault(t => t.TicketType == 0 && t.TickertNo == qrCodesModel.Key);
                    if (order == null)//活动码为一人一码一订单 不能重复下单
                    {
                        // 下鲸图进厅订单（保存会员进厅卡号、JSJID、进厅次数、是否含本人、会员类型）
                        order = _ctx.OrderChannelVipHalls.Add(new Data.Entities.VIPHalls.OrderChannelVipHall()
                        {
                            TicketType = ticketType,
                            TickertNo = qrCodesModel.Key,
                            Channel = request.channel,
                            UseCount = request.useCount,
                            UseTime = Convert.ToDateTime(request.useTime),
                            ProductUniqueCode = request.productUniqueCode,
                            IsSelf = request.isSelf,
                            VipHallId = tcjtVIPHall.VipHallId.Value,
                            PackServiceId = tcjtVIPHall.PackServiceId ?? 0,
                            IsDelete = 0,
                            CreateTime = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            CardNumber = cardNumber,
                            IsSelfUseNum = isUseNum
                        });
                        _ctx.SaveChanges();
                        serialID = GenSerialID("TCJT", order.OrderID);
                        order.SerialID = serialID;
                        _ctx.SaveChanges();
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(order.TCJTTickerNo))
                        {
                            throw new JSJException("次劵码已使用");
                        }
                        serialID = order.SerialID;
                    }
                }
                    #endregion

                    #region 金色会员使用
                    else if (ticketType == 1)
            {
                var order = _ctx.OrderChannelVipHalls.FirstOrDefault(t => t.TicketType == 1 && t.TickertNo == qrCodesModel.Key && t.TCJTTickerNo == null);
                if (order == null)//活动码为一人一码一订单 不能重复下单
                {
                    var toDay = DateTime.Now.Date;
                    var orders = _ctx.OrderChannelVipHalls.Where(t => t.TicketType == 1 && t.TickertNo == qrCodesModel.Key && t.CreateTime > toDay).AsQueryable().ToList();
                    if (orders.Any(t => t.IsSelfUseNum == false && t.IsSelf == 1) && request.isSelf == 1)//含本人，且本人不扣次数
                    {
                        throw new JSJException("会员本人每天仅可进厅一次");
                    }

                    // 下鲸图进厅订单（保存会员进厅卡号、JSJID、进厅次数、是否含本人、会员类型）
                    order = _ctx.OrderChannelVipHalls.Add(new Data.Entities.VIPHalls.OrderChannelVipHall()
                    {
                        TicketType = ticketType,
                        TickertNo = qrCodesModel.Key,
                        Channel = request.channel,
                        UseCount = request.useCount,
                        UseTime = Convert.ToDateTime(request.useTime),
                        ProductUniqueCode = request.productUniqueCode,
                        IsSelf = request.isSelf,
                        VipHallId = tcjtVIPHall.VipHallId.Value,
                        PackServiceId = tcjtVIPHall.PackServiceId ?? 0,
                        IsDelete = 0,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        CardNumber = cardNumber,
                        IsSelfUseNum = isUseNum
                    });
                    _ctx.SaveChanges();
                    serialID = GenSerialID("TCJT", order.OrderID);
                    order.SerialID = serialID;
                    _ctx.SaveChanges();
                }
                else
                {
                    serialID = order.SerialID;
                }
            }
                    #endregion

                    #region 贵宾厅订单使用
                    else if (ticketType == 2)
            {
                var orders = _ctx.OrderChannelVipHalls.Where(t => t.TicketType == 2 && t.TickertNo == qrCodesModel.Key).AsQueryable();

                var order = orders.FirstOrDefault(t => t.TCJTTickerNo == null);

                if (order == null)//活动码为一人一码一订单 不能重复下单
                {
                    var uesdCount = orders.Select(t => t.UseCount).ToList().Sum();
                    if (orderCount < (uesdCount + request.useCount))
                    {
                        var canCount = (orderCount - uesdCount);
                        throw new JSJException(string.Format("订单剩余可进厅次数为{0}", canCount < 0 ? 0 : canCount));
                    }

                    // 下鲸图进厅订单（保存会员进厅卡号、JSJID、进厅次数、是否含本人、会员类型）
                    order = _ctx.OrderChannelVipHalls.Add(new Data.Entities.VIPHalls.OrderChannelVipHall()
                    {
                        TicketType = ticketType,
                        TickertNo = qrCodesModel.Key,
                        Channel = request.channel,
                        UseCount = request.useCount,
                        UseTime = Convert.ToDateTime(request.useTime),
                        ProductUniqueCode = request.productUniqueCode,
                        IsSelf = request.isSelf,
                        VipHallId = tcjtVIPHall.VipHallId.Value,
                        PackServiceId = tcjtVIPHall.PackServiceId ?? 0,
                        IsDelete = 0,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        CardNumber = cardNumber,
                        IsSelfUseNum = isUseNum
                    });
                    _ctx.SaveChanges();
                    serialID = GenSerialID("TCJT", order.OrderID);
                    order.SerialID = serialID;
                    _ctx.SaveChanges();
                }
                else
                {
                    serialID = order.SerialID;
                }
            }
                    #endregion

                    #region 超级空客会员使用
                    else if (ticketType == 3)
            {
                var order = _ctx.OrderChannelVipHalls.FirstOrDefault(t => t.TicketType == 3 && t.TickertNo == qrCodesModel.Mobile && t.TCJTTickerNo == null);
                if (order == null)//活动码为一人一码一订单 不能重复下单
                {
                    // 下鲸图进厅订单（保存会员进厅卡号、JSJID、进厅次数、是否含本人、会员类型）
                    order = _ctx.OrderChannelVipHalls.Add(new Data.Entities.VIPHalls.OrderChannelVipHall()
                    {
                        TicketType = ticketType,
                        TickertNo = qrCodesModel.Mobile,
                        Channel = request.channel,
                        UseCount = request.useCount,
                        UseTime = Convert.ToDateTime(request.useTime),
                        ProductUniqueCode = request.productUniqueCode,
                        IsSelf = request.isSelf,
                        VipHallId = tcjtVIPHall.VipHallId.Value,
                        PackServiceId = tcjtVIPHall.PackServiceId ?? 0,
                        IsDelete = 0,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        CardNumber = cardNumber,
                        IsSelfUseNum = isUseNum
                    });
                    _ctx.SaveChanges();
                    serialID = GenSerialID("TCJT", order.OrderID);
                    order.SerialID = serialID;
                    _ctx.SaveChanges();
                }
                else
                {
                    serialID = order.SerialID;
                }
            }
                    #endregion
                response.resCode = "100";
                response.thirdSerialId = serialID;
            }
            else
            {
                throw new JSJException("非金色有效二维码");
            }
        }
        //catch (System.Data.Entity.Validation.DbEntityValidationException ex)
        //{
        //    Console.Write(ex.Message);
        //}
        catch (Exception ex)
        {
            response.resCode = "-1000";
            response.resMsg = ex.Message;
            base.MoLog.ThirdResponseObj = ex;
            base.MoLog.LogLevel = EnumHelper.CommonEnum.LogLevel.Error;
        }
        finally
        {
            base.MoLog.StackTrace = new System.Diagnostics.StackTrace();
            base.WriteLog<KTTwoDieCodeValidReq, KTTwoDieCodeValidResp>(request, response);
        }
        return response;
    }*/

    /// <summary>
    /// 判断渠道是否能进入鲸图厅
    /// </summary>
    /// <param name="customerType">0 大客户  1 金色会员 2 app零售订单 3 空铁会员</param>
    /// <returns></returns>
    public boolean CheckCanEnterTCJTHall(int customerType)
    {
        boolean result = false;
        switch (customerType)
        {
            case 0:
                result = openBigCustomer;
                break;
            case 1:
                result = openGoldenMember;
                break;
            case 2:
                result = openKTVipHallOrder;
                break;
            case 3:
                result = openKTMember;
                break;
            default:
                break;
        }
        return result;
    }


    /**
     * 贵宾厅二维码加密
     *
     * @param qrCodesNewModel 二维码对象
     * @return
     */
    public String encryptVipHallQrCode(QRCodesNewModel qrCodesNewModel)
    {
        String qrCodeInfo = MessageFormat.format("{0}|{1}|{2}|{3}", qrCodesNewModel.QRCodesSource.getValue(), qrCodesNewModel.Key, qrCodesNewModel.CurrentTimeStamp, qrCodesNewModel.SourceWay);
        return AesUtil.encrypt(MessageFormat.format("{0}${1}", qrCodeInfo, DigestUtils.md5Hex(qrCodeInfo + MEMBERCode_MD5_KEY)), this.QRCODE_ENCRYPT_KEY);
    }

    /**
     * 贵宾厅数据解密
     *
     * @param encryptInfo 二维码对象加密字符串
     * @return
     */

    public QRCodesNewModel decryptVipHallQrCode(String encryptInfo)
    {
        String encryptString = AesUtil.decrypt(encryptInfo, this.QRCODE_ENCRYPT_KEY);
        String[] arrEncrypt = encryptString.split("\\$");
        String qrCodeInfo = arrEncrypt[0];
        String md5QrcodeInfo = arrEncrypt[1];
        String[] arrQrCode = qrCodeInfo.split("\\|");
        QRCodesNewModel qrCodesNewModel = new QRCodesNewModel();
        qrCodesNewModel.QRCodesSource = QRCodesSource.values()[Integer.valueOf(arrQrCode[0])];
        qrCodesNewModel.Key = arrQrCode[1];
        qrCodesNewModel.CurrentTimeStamp = Long.valueOf(arrQrCode[2].replace(",", ""));
        qrCodesNewModel.SourceWay = BusinessTypeConstants.SourceWay.valueOf(arrQrCode[3]);
        String qrFormatInfo = MessageFormat.format("{0}|{1}|{2}|{3}", qrCodesNewModel.QRCodesSource.getValue(), qrCodesNewModel.Key, qrCodesNewModel.CurrentTimeStamp, qrCodesNewModel.SourceWay);
        if (!DigestUtils.md5Hex(qrFormatInfo + MEMBERCode_MD5_KEY).equals(md5QrcodeInfo))
        {
            throw new RuntimeException("二维码无效");
        }
        if ((qrCodesNewModel.CurrentTimeStamp + 60 * 1000) > DateUtils.getNowDate().getTime())
        {
            throw new RuntimeException("二维码已经过期");
        }
        return qrCodesNewModel;
    }

    public String getJTChannelCode()
    {
        return this.tcjtChannel;
    }

    /*public static void main(String[] args)
    {
        QRCodesNewModel qrCodesNewModel = new QRCodesNewModel();
        qrCodesNewModel.CurrentTimeStamp = DateUtils.getNowDate().getTime();
        qrCodesNewModel.SourceWay = Constant.SourceWay.App;
        qrCodesNewModel.Key = "12121212";
        qrCodesNewModel.Mobile = "18310769919";
        qrCodesNewModel.QRCodesSource = QRCodesSource.AirwayKeeperVipHallOrder;
        JingTuHeXiaoUtil jingTuHeXiaoUtil = new JingTuHeXiaoUtil();
        String qrCodeString = JingTu.getInstance().encryptVipHallQrCode(qrCodesNewModel);
        QRCodesNewModel tmpQrCode = JingTu.getInstance().decryptVipHallQrCode(qrCodeString);
        return;
    }*/
}
